from sqlalchemy import text
from flask_login import  UserMixin,login_manager
from extensions import login_manager,db,i_maotai_rob
from datetime import datetime
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def get_db_config(app):
    # 从数据数据库中读取配置并赋值给i_maotai_rob
    with app.app_context():
        sql = """SELECT * FROM config """
        result = db.session.execute(text(sql))
        config = [dict(row._mapping) for row in result]
        i_maotai_rob._load_config_from_db(config_list=config)


# 定义用户模型
class User(UserMixin):
    def __init__(self, id, username, password,role):
        self.id = id
        self.username = username
        self.password = password
        self.role = role


@login_manager.user_loader
def load_user(user_id):
    # 这里应该从数据库加载用户
    sql = f"""
            SELECT 
                id, username, password ,role
            FROM 
                users 
            WHERE id = {user_id}
        """
    result = db.session.execute(text(sql))
    user_data = [dict(row._mapping) for row in result]
    if user_data:
        user_data = user_data[0]
        return User(user_data['id'], user_data['username'], user_data['password'],user_data['role'])
    
    return None

def save_imaotai_log(imaotai_user_id,users_id,message):
    """ 抢购日志保存到数据库 """
    formatted_date = datetime.now().strftime("%Y-%m-%d")
    sql = f"""
            INSERT INTO
                imaotai_log
                (imaotai_user_id,message,created_date,users_id)
            VALUES
                ({imaotai_user_id}, '{message}','{formatted_date}',{users_id});
        """
    db.session.execute(text(sql))
    db.session.commit()


def send_email_reminder(email, username, expire_time):
    """
    发送token过期提醒邮件 (使用QQ邮箱)

    参数:
        email: 收件人邮箱
        username: 用户名
        expire_time: token过期时间
    """
    try:
        # QQ邮箱配置
        SMTP_SERVER = 'smtp.qq.com'  # QQ邮箱SMTP服务器
        SMTP_PORT = 587  # QQ邮箱SMTP端口
        SENDER_EMAIL = '215775468@qq.com'  # 你的QQ邮箱地址
        SENDER_PASSWORD = 'vzggwiyfbhkpcbai'  # QQ邮箱授权码

        # 注意：QQ邮箱授权码获取方法：
        # 1. 登录 https://mail.qq.com
        # 2. 进入 设置 -> 账户
        # 3. 找到 "POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务"
        # 4. 点击 "生成授权码" 获取16位授权码

        # 创建邮件
        msg = MIMEMultipart()
        msg['From'] = SENDER_EMAIL
        msg['To'] = email
        msg['Subject'] = 'Token过期提醒'

        # 邮件正文
        body = f"""
        <html>
            <body style="font-family: Arial, sans-serif; color: #333;">
                <div style="max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #ddd; border-radius: 5px;">
                    <h2 style="color: #d9534f;">⚠️ Token过期提醒</h2>
                    <p>尊敬的 <strong>{username}</strong>，</p>
                    <p>您的登录Token将在以下时间过期：</p>
                    <p style="background-color: #f5f5f5; padding: 10px; border-left: 4px solid #d9534f; font-size: 16px;">
                        <strong>{expire_time}</strong>
                    </p>
                    <p>请及时重新登录以继续使用服务。</p>
                    <hr style="border: none; border-top: 1px solid #ddd; margin: 20px 0;">
                    <p style="font-size: 12px; color: #999;">此邮件由系统自动发送，请勿回复。</p>
                </div>
            </body>
        </html>
        """

        msg.attach(MIMEText(body, 'html', 'utf-8'))

        # 使用STARTTLS
        server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
        server.starttls()  # 启用TLS加密
        server.login(SENDER_EMAIL, SENDER_PASSWORD)
        server.send_message(msg)
        server.quit()

        print(f"✓ 邮件已成功发送至 {email}")
        return True

    except Exception as e:
        print(f"✗ 邮件发送失败: {e}")
        return False
